#include <iostream>
#define RESIZE_STEP 5
using namespace std;

template <typename T>
class DynamicArray {
	private:
    	T* data;  // 指向动态分配数组的指针
    	int size;     // 数组当前大小
    	int capacity; // 数组容量

	public:
    	DynamicArray(size_t initCapacity) : size(0), capacity(initCapacity)
		{
        	data = size == 0 ? nullptr : new T[capacity];
    	}

		DynamicArray(const DynamicArray<T> &src)
		{
			int i;

			data = new T[src.getSize()];
			for (i = 0; i < src.getSize(); i++) {
				data[i] = src[i];
			}
		}

	    ~DynamicArray()
		{
    	    delete[] data;
    	}
		
		T &operator[](int index)
		{
			return data[index];
		}

		const T &operator[](int index) const
		{
			return data[index];
		}

		DynamicArray<T> &operator=(const DynamicArray<T> &src)
		{
			int i;

			// 调整数组容量
			resize(src.getCapacity());

			// 更新实际的元素个数
			size = src.getSize();

			for (i = 0; i < src.getSize(); i++) {
				data[i] = src.data[i];
			}

			return *this;
		}

	    int append(const T &value)
		{
    	    if (size == capacity) {
        	    // 如果数组已满，则增加容量
            	resize(capacity + RESIZE_STEP);
        	}
        	data[size++] = value;

			return 0;
    	}

	    int insert(int index, const T &value)
		{
			int i;

    	    if (size == capacity) { // 若已满则扩容
        	    resize(capacity + RESIZE_STEP);
        	}
        	for (i = size; i > index; --i) {
            	data[i] = data[i - 1];
        	}
        	data[index] = value;
        	size += 1;

			return 0;
    	}

    	int remove(int index)
		{
			int i;

        	for (i = index; i < size - 1; ++i) {
            	data[i] = data[i + 1];
        	}
        	size -= 1;

			return 0;
    	}

	    int getSize() const
		{
    	    return size;
    	}

	    int getCapacity() const
		{
    	    return capacity;
    	}

		template <typename TFRIEND>
		friend ostream &operator<<(ostream &out, const DynamicArray<TFRIEND> &arr);

	private:
	    int resize(int newCapacity)
		{
    	    T* newData = newCapacity == 0 ? nullptr : new T[newCapacity];
			int i;

        	for (i = 0; i < size && i < newCapacity; ++i) {
            	newData[i] = data[i];
        	}
        	delete[] data;
        	data = newData;

			cout << "调整大小：" << capacity << " -> " << newCapacity << endl;

        	capacity = newCapacity;

			return 0;
    	}
};

template <typename T>
ostream &operator<<(ostream &out, const DynamicArray<T> &arr)
{
	int i;
	for (i = 0; i < arr.getSize(); i++) {
		out << arr.data[i] << ' ';
	}
	
	return out;
}

int main() {
    DynamicArray<int> arr(0);
	DynamicArray<int> arr2(0);
	int i;

    arr.append(10);
    arr.append(20);
    arr.append(30);
	cout << arr << endl;

	cout << "在下标为1处插入15" << endl;
    arr.insert(1, 15);
    cout << arr << endl;

	cout << "删除下标为2的元素" << endl;
    arr.remove(2);
	cout << arr << endl;

	arr2 = arr;

	cout << "在末尾连续添加10个元素" << endl;
	for (i = 0; i < 10; i++) {
		arr.append(100 + i);
	}
	cout << arr << endl;

	cout << "Assigned: " << arr2 << endl;

	return 0;
}

